package com.btl.component.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.UUID;

import static org.springframework.util.StringUtils.hasLength;

public class TraceFilter implements Filter {
    private static final String TRACE_ID_HEADER = "X-Trace-Id";
    private static final String TRACE_ID_KEY = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        try {
            // 从Header获取或生成TraceID
            String traceId = ((HttpServletRequest) request).getHeader(TRACE_ID_HEADER);
            if (!StringUtils.hasLength(traceId)) {
                traceId = UUID.randomUUID().toString().replace("-", "");
            }
            // 存入MDC和Response Header
            MDC.put(TRACE_ID_KEY, traceId);
            ((HttpServletResponse) response).addHeader(TRACE_ID_HEADER, traceId);

            chain.doFilter(request, response);
        } finally {
            MDC.remove(TRACE_ID_KEY); // 必须清理防止内存泄漏
        }
    }
}
